package com.jiesai.amaq.canines.framework.security.service;


import java.util.List;

import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.cas.authentication.CasAssertionAuthenticationToken;
import org.springframework.security.core.userdetails.AuthenticationUserDetailsService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.jiesai.amaq.canines.common.enums.UserStatus;
import com.jiesai.amaq.canines.common.exception.ServiceException;
import com.jiesai.amaq.canines.common.utils.StringUtils;
import com.jiesai.amaq.canines.framework.security.LoginUser;
import com.jiesai.amaq.manager.model.SysUser;
import com.jiesai.amaq.manager.model.SysUserOrg;
import com.jiesai.amaq.manager.service.SysUserOrgService;
import com.jiesai.amaq.manager.service.SysUserService;

@Service
public class CasUserDetailsService implements AuthenticationUserDetailsService<CasAssertionAuthenticationToken> {

	private static final Logger log = LoggerFactory.getLogger(CasUserDetailsService.class);

//	@Autowired
//	private ISysUserService userService;
	
	@DubboReference
	private SysUserService sysUserService;
	
	@DubboReference
	private SysUserOrgService sysUserOrgService;

	@Autowired
	private SysPermissionService permissionService;
	
	

	@Override
	public UserDetails loadUserDetails(CasAssertionAuthenticationToken token) throws UsernameNotFoundException {
		String username = token.getName();
		//SysUser user = userService.selectUserByUserName(username);
		SysUser user = null;
		try {
			user = sysUserService.finSysUserByLoginAccount(username);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (StringUtils.isNull(user)) {
			log.info("登录用户：{} 不存在.", username);
			throw new ServiceException("登录用户：" + username + " 不存在");
		} else if (UserStatus.DELETED.getCode().equals(user.getStatus())) {
			log.info("登录用户：{} 已被删除.", username);
			throw new ServiceException("对不起，您的账号：" + username + " 已被删除");
		} else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
			log.info("登录用户：{} 已被停用.", username);
			throw new ServiceException("对不起，您的账号：" + username + " 已停用");
		}

		return createLoginUser(user);
	}

	public UserDetails createLoginUser(SysUser user) {
		SysUserOrg sysUserOrg = new SysUserOrg();
		sysUserOrg.setUserId(user.getId());
		List<SysUserOrg> orgList = sysUserOrgService.selectList(sysUserOrg);
		return new LoginUser(user.getId(), orgList, user, permissionService.getMenuPermission(user));
	}
}

